package com.base.web.core.config.datasource;


import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;


/**
 * Created with IntelliJ IDEA.
 * Description:从数据源配置
 *
 * @Author: rentie
 * @Date: 2018/8/8 10:38
 */
//@Configuration
// 扫描 Mapper 接口并容器管理
//@MapperScan(basePackages = {"com.base.web.dao.cluster"}, sqlSessionTemplateRef = "clusterSqlSessionTemplate")
public class ClusterDataSourceConfig {

    private Logger logger = LoggerFactory.getLogger(ClusterDataSourceConfig.class);


    // 精确到 cluster 目录，以便跟其他数据源隔离
    static final String MAPPER_LOCATION = "classpath:mappers/cluster/**/*.xml";
    static final String TYPE_ALIASES_PACKAGE = "com.base.web.auth.model.cluster";


    @Bean("clusterDataSource")
    @ConfigurationProperties("spring.datasource.druid.cluster")
    public DataSource clusterDataSource(){
        logger.info("cluster dataSource init");
        return DruidDataSourceBuilder.create().build();
    }


    @Bean(name = "clusterTransactionManager")
    public DataSourceTransactionManager clusterTransactionManager() {

        return new DataSourceTransactionManager(clusterDataSource());
    }

    @Bean(name = "clusterSqlSessionFactory")
    public SqlSessionFactory clusterSqlSessionFactory(@Qualifier("clusterDataSource") DataSource dataSource)
            throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        sessionFactory.setTypeAliasesPackage(ClusterDataSourceConfig.TYPE_ALIASES_PACKAGE);
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources(ClusterDataSourceConfig.MAPPER_LOCATION));
        return sessionFactory.getObject();
    }

    @Bean(name = "clusterSqlSessionTemplate")
    public SqlSessionTemplate clusterSqlSessionTemplate(@Qualifier("clusterSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}